// 定义游戏玩家类
var pBox = require("planck-js")
var Box2D = require("box2dweb")
var b2Vec2 = pBox.Vec2
    /* , b2BodyDef = Box2D.Dynamics.b2BodyDef */
    , b2Body = pBox.Body
    /* , b2FixtureDef = Box2D.Dynamics.b2FixtureDef */
    /* , b2Fixture = Box2D.Dynamics.b2Fixture */
    , b2World = pBox.World
    /* , b2MassData = Box2D.Collision.Shapes.b2MassData */
    , b2PolygonShape = pBox.Box
    , b2CircleShape = pBox.Circle
    /* , b2DebugDraw = Box2D.Dynamics.b2DebugDraw
    , b2MouseJointDef = Box2D.Dynamics.Joints.b2MouseJointDef
    , b2WeldJointDef = Box2D.Dynamics.Joints.b2WeldJointDef
    , b2PrismaticJointDef = Box2D.Dynamics.Joints.b2PrismaticJointDef
    , b2DistanceJointDef = Box2D.Dynamics.Joints.b2DistanceJointDef */
    /* , b2ContactListener = Box2D.Dynamics.b2ContactListener */
    ;
class PhyicWorld {
    //构造函数
    constructor() {
        this.m_World = null;
        this.m_RoomPhyData = [];
    }
    initPhyicWorld(initData) {
        var data = initData;
        this.m_World = new b2World(
            new b2Vec2(0, 50)    //gravity  重力的方向，力度 单位牛，10就是重力加速度G
            , false              //allow sleep
        );
        data.forEach((element, n) => {
            this.buildLand(element, n);
        });
        this.m_World.on('begin-contact', this.endContact)
        var self = this;
        setInterval(function () { self.GlobalUpdate.call(self) }, 1000 / 30);
    }
    buildLand(data, n) {
        var x = data.pos.x;
        var y = data.pos.y;
        var width = data.size.x;
        var height = data.size.y;
        var ground = this.m_World.createBody({
            type: "static",
            position: b2Vec2(x, y),
        });
        var fixDef = {
            shape: pBox.Box(width, height),
            density: 1.0,//密度
            friction: 0.1,//摩擦力
            restitution: n == 7 ? 1 : 1//弹性系数
        }
        ground.createFixture(fixDef);
        global["land" + n] = ground;
        global["land" + n].setUserData(n);
    }
    GlobalUpdate() {
        var a = 1 / 30;
        this.m_World.step(
            a   //frame-rate
            , 10      //velocity iterations
            , 10      //position iterations
        );
    }
    endContact(contact) {
        var bodyAData = contact.getFixtureA().getBody().getUserData();
        var ballBady = contact.getFixtureB().getBody();
        if (ballBady.getUserData() != "ball") return;
        switch (bodyAData) {
            case 7:
                var v_value = Math.abs(ballBady.m_linearVelocity.y);
                if (v_value < 20) {
                    ballBady.m_linearVelocity.y = 20
                    // ballBady.m_linearVelocity.setZero();
                    // ballBady.applyLinearImpulse(new b2Vec2(0, -150), ballBady.getWorldCenter());
                }
                break;
            case 1:
                console.log("右-玩家得分");
                var room = g_GameRoomList[ballBady.roomId];
                g_PWInstance.newRound(room);
                room.SetRoundStatus(ROUND_OVER);
                room.goal(1)
                var goalData = room.GetGoalData()
                io.to(room.RoomId).emit('set_score', { id: 1, "goalData": goalData });//xxx加入了房间 前端显示
                break;
            case 4:
                console.log("左-玩家得分");
                var room = g_GameRoomList[ballBady.roomId];
                g_PWInstance.newRound(room);
                room.SetRoundStatus(ROUND_OVER);
                room.goal(0)
                var goalData = room.GetGoalData()
                io.to(room.RoomId).emit('set_score', { id: 0, "goalData": goalData });//xxx加入了房间 前端显示
                break;
            default:
                break;
        }

    }
    buildRoomPhyicData(roomId) {
        var player1 = {
            pos: { x: 27, y: 27 },
            GetPosition: function () {
                return this.pos;
            },
            SetPosition: function (pos) {
                this.pos = pos;
            }
        };
        var player2 = {
            pos: { x: 45, y: 27 },
            GetPosition: function () {
                return this.pos;
            },
            SetPosition: function (pos) {
                this.pos = pos;
            }
        };
        //球
        var keyBoll = this.m_World.createBody({
            linearDamping:0.1,
            type: "dynamic",
            position: b2Vec2(900 / 30, 300 / 30),
        });
        var fixDef = {
            filterGroupIndex : -1,
            shape: pBox.Circle(1),
            density: 1,//密度
            friction: 0.2,//摩擦力
            restitution: 1//弹性系数
        }
        keyBoll.createFixture(fixDef);
        keyBoll.setUserData("ball");
        keyBoll.roomId = roomId;
        var phydata = { ball: keyBoll, p1: player1, p2: player2 };
        this.m_RoomPhyData[roomId] = phydata;
        return phydata;
    }
    newRound(room) {
        let roomId = room.GetRoomId();
        var ball = this.m_RoomPhyData[roomId].ball;
        // ball.SetAwake(false);
        ball.m_linearVelocity.setZero();
        setTimeout(() => {
            // ball.SetAwake(true);
            var pos = { x: 950 / 30, y: 300 / 30 };
            ball.setPosition(pos);
            ball.m_linearVelocity.setZero();
            ball.applyLinearImpulse(new b2Vec2(0, -100), ball.getWorldCenter())
            io.to(roomId).emit('new_round');//xxx加入了房间 前端显示
            room.SetRoundStatus(ROUND_PLAYING);
        }, 1 * 1000);
    }

}
module.exports = PhyicWorld;